from Editor import GetSelection,LineStart,LineEnd,GetText,InsertText,SetSelection
import string,Editor

def DoComment():
	ft=Editor.GetFileType()
	try:
		gCommands[ft][0]()
	except:
		CPPComment()
 
def DoUnComment():
	ft=Editor.GetFileType()
	try:
		gCommands[ft][1]()
	except:
		CPPUnComment()
 
def HashComment():
	LineComment("#")
def HashUnComment():
	LineUnComment("#")
 
def F77Comment():
	LineComment("C")
def F77UnComment():
	LineUnComment("C")
 
def F90Comment():
	LineComment("!")
def F90UnComment():
	LineUnComment("!")
 
def OQLComment():
	LineComment("--")
def OQLUnComment():
	LineUnComment("--")
 
def CPPComment():
	if Editor.Search("/\*",0) != (-1,-1) and Editor.Search("//",0) == (-1,-1):
		CComment()
	else:
		LineComment("//")
 
def CPPUnComment():
	if Editor.Search("/\*",0) != (-1,-1) and Editor.Search("//",0) == (-1,-1):
		CUnComment()
	else:
		LineUnComment("//")

def CobolComment():
	LineComment("*")
def CobolUnComment():
	LineUnComment("*")
 
def CComment():
	start,end=GetSelection()
	txt=GetText(start,end)
	if txt and txt[-1]=='\n':
		txt=txt[:-1]
		end=end-1
	SetSelection(end,end)
	InsertText("*/")
	SetSelection(start,start)
	InsertText("/*")
	SetSelection(start,end+4)
 
def CUnComment():
	start,end=GetSelection()
	start=LineStart(start)
	f,t=Editor.Search("/\*",start)
	if f>=0:
		SetSelection(f,t)
		InsertText("")
	
	end=LineStart(end)
	f,t=Editor.Search("\*/",start)
	if f>=0:
		SetSelection(f,t)
		InsertText("")
	SetSelection(start,end-4)

def LineComment(prefix):
	start,end=GetSelection()
	start=LineStart(start)
	txt=GetText(start,end)
	if txt and txt[-1]=='\n':
		txt=txt[:-1]
		end=end-1
	lines=string.splitfields(txt,"\n")
	commented=""
	for line in lines:
		commented=commented+prefix+line+"\n"
	commented=commented[:len(commented)-1]
	SetSelection(start,end)
	InsertText(commented)
	SetSelection(start,start+len(commented))

def LineUnComment(prefix):
	start,end=GetSelection()
	start=LineStart(start)
	txt=GetText(start,end)
	lines=string.splitfields(txt,"\n")
	commented=""
	prefixlen=len(prefix)
	for line in lines:
		if line[:prefixlen]== prefix:
			line=line[prefixlen:]
		commented=commented+line+"\n"
	commented=commented[:len(commented)-1]
	if commented!=txt:
		SetSelection(start,end)
		InsertText(commented)
		SetSelection(start,start+len(commented))

gCommands={
	"Python" : (HashComment, HashUnComment),
	"Implementation": (CPPComment, CPPUnComment),
	"Header":  (CPPComment, CPPUnComment),
	"Make":  (HashComment, HashUnComment),
	"Make Support": (HashComment, HashUnComment),
	"Shell": (HashComment, HashUnComment),
	"OQL queries": (OQLComment, OQLUnComment),
	
}
